package com.cxc.canal.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.xpand.starter.canal.annotation.ListenPoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;


//@CanalEventListener
@Slf4j
public class CanalDataEventListener {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //自定义数据库的 操作来监听
    @ListenPoint(destination = "example",
            schema = "changgou_content",
            table = {"tb_content", "tb_content_category"},
            eventType={CanalEntry.EventType.UPDATE,
                    CanalEntry.EventType.DELETE,
                    CanalEntry.EventType.INSERT})
    public void onEventCustomUpdate(CanalEntry.EventType eventType, CanalEntry.RowData rowData){

        log.debug("监听广告表内容有改变------开始处理");
        //1.获取列名 为category_id的值
        String categoryId = getColumnValue(eventType,rowData);
        log.debug("监听广告表内容哪类广告ID------categoryId:{}",categoryId);
        System.out.println("监听广告表内容哪类广告ID------"+categoryId);

        //2.调用feign 获取该分类下的所有的广告集合
//        Result<List<Content>> categoryResult = null;
        /*try {
            categoryResult = contentFeign.findByCategory(Long.valueOf(categoryId));
        }catch (Exception e){
            e.printStackTrace();
        }*/
//        log.debug("远程调用微服务------categoryResult：{}",categoryResult);
//        List<Content> data = categoryResult.getData();
//        System.out.println("data:----------"+data);
        //3.使用redisTemplate存储到redis中
        stringRedisTemplate.boundValueOps("content_"+categoryId).set(JSON.toJSONString(null));


    }


    private String getColumnValue(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
        String categoryId = "";
        //判断 如果是删除  则获取beforlist
        if(eventType == CanalEntry.EventType.DELETE){
            for (CanalEntry.Column column: rowData.getBeforeColumnsList()){
                if (column.getName().equalsIgnoreCase("category_id")){
                    categoryId = column.getValue();
                    return categoryId ;
                }
            }
        }else{
            //判断 如果是添加 或者是更新 获取afterlist
            for (CanalEntry.Column column : rowData.getAfterColumnsList()) {
                if (column.getName().equalsIgnoreCase("category_id")) {
                    categoryId = column.getValue();
                    return categoryId;
                }
            }
        }
        return categoryId;
    }


}
